package com.seeyon.apps.extracontract.manager.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.seeyon.apps.brwh.kit.StrKit;
import com.seeyon.apps.extracontract.manager.ExtraContractManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import www.seeyon.com.utils.UUIDUtil;

import com.seeyon.apps.cip.util.FileUtils;
import com.seeyon.apps.extracontract.thread.BackThread;
import com.seeyon.apps.extracontract.util.BookMarksUtil;
import com.seeyon.apps.extracontract.util.FormUtils;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.filemanager.dao.AttachmentDAO;
import com.seeyon.ctp.common.filemanager.manager.AttachmentManager;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.services.FileDownloadExporter;
import com.seeyon.ctp.services.FileUploadExporter;

public class ExtraContractManagerImpl implements ExtraContractManager {
	
	private final static Log log = LogFactory.getLog(ExtraContractManagerImpl.class);
	
	private AttachmentManager attachmentManager;
	private FileManager fileManager;
	private AttachmentDAO attachmentDAO;
	
	/**
	 * 套红
	 * 
	 * @param formBean
	 * @return
	 */
	public Map<String, Object> taoHong(FormBean formBean, FormDataMasterBean formDataMasterBean){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			FormUtils formUtils = new FormUtils(formBean, formDataMasterBean);
			String contractTemplateId = StrKit.str(formDataMasterBean.getFieldValue(formUtils.getField("合同范本")));
			if(!"".equals(contractTemplateId)) {
				
				Map<Long, Map<String, Attachment>> updateMap = new LinkedHashMap<Long, Map<String, Attachment>>();
				String type = "";
				Map<String, Attachment> subIdMap = dealTaoHong(Long.parseLong(contractTemplateId),type,formBean,formDataMasterBean,formUtils);
				updateMap.put(formDataMasterBean.getId(), subIdMap);
				
				// -- 执行入库操作
				BackThread backThread = new BackThread();
				backThread.setBean(formDataMasterBean);
				backThread.setFormBean(formBean);
				backThread.setUpdateMap(updateMap);
				backThread.start();
				// -- 异步执行入库操作
				resultMap.put("success", true);
			}
		} catch (Exception e) {
			log.info("", e);
			
		}
		return null;
		
	}

	/**
	 * 套红处理
	 * @param subRefId
	 * @param type
	 * @param formBean
	 * @param data
	 * @param formUtils
	 * @throws FileNotFoundException 
	 */
	private Map<String, Attachment> dealTaoHong(Long subRefId, String type, FormBean formBean,FormDataMasterBean data, FormUtils formUtils) throws Exception {
		List<FormFieldBean> mainFields = formBean.getMasterTableBean().getFields();
		
		// -- 主表套红字段合集
		Map<String, String> main = new HashMap<String, String>();
		
		// -- 名字表套红字段合计
		Map<String, List<Map<String, String>>> subTableDatas = new LinkedHashMap<String, List<Map<String, String>>>();
		
		// -- 主表数据套红
		for (FormFieldBean mainField : mainFields) {
			if(mainField.getDisplay().contains(type)){
				main.put(mainField.getDisplay(), formUtils.getValue(mainField.getDisplay()));
			}
		}
		// -- 明细表套红
		List<FormTableBean> subTables = formBean.getSubTableBean();
		// -- 遍历明细表，确认哪个明细表需要进行套红
		for (FormTableBean subTable : subTables) {
			if(subTable.getDisplay().contains(type)){
				// -- 如果有标识，则说明为模板明细表
				List<Map<String, String>> sonlist = new ArrayList<Map<String, String>>();
				// -- 获取对应明细表下的数据集合
				List<FormDataSubBean> subBeans = data.getSubData(subTable.getTableName());
				for (FormDataSubBean formDataSubBean : subBeans) {
					Map<String, String> sonMap = new HashMap<String, String>();
					List<FormFieldBean> subFields = subTable.getFields();
					// -- 遍历明细表字段 进行需要桃红字段处理
					for (FormFieldBean formFieldBean : subFields) {
						String value = null;
						if(formDataSubBean.getFieldValue(formFieldBean.getName())!=null){
							value = formDataSubBean.getFieldValue(formFieldBean.getName()).toString();
						}
						sonMap.put(formFieldBean.getDisplay(), value);
					}
					sonlist.add(sonMap);
				}
				// -- 插入明细表数据
				subTableDatas.put(subTable.getDisplay(), sonlist);
			}
		}
		
		// -- 数据封装后，进行套红处理 并返回套红后的附件文件，并转换成PDF
		List<Long> subIds = new ArrayList<Long>();
		subIds.add(subRefId);
		List<Attachment> attachments = attachmentManager.getBySubReference(subIds);
		if(attachments != null && attachments.size() > 0){
			
			V3XFile v3xFile = fileManager.getV3XFile(attachments.get(0).getFileUrl());
			String filePath = AppContext.getCfgHome().getCanonicalPath();
			filePath = filePath.replace("WEB-INF" + File.separator + "cfgHome", "fileTemp" + File.separator);
			String basePath = filePath + File.separator;
			File newFile = new File(basePath + attachments.get(0).getReference()+"_"+v3xFile.getFilename());
			FileOutputStream out = new FileOutputStream(newFile.getPath());
			FileDownloadExporter downloadExporter = new FileDownloadExporter();
			downloadExporter.processDownload(v3xFile.getId()+"", out);
			
			File toFile = new File(basePath + "new_"+v3xFile.getFilename());
			// -- 套红 重新上传
			BookMarksUtil.addBookMarks(newFile, toFile, main, subTableDatas);
			OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");
		    V3xOrgMember v3xOrgMember = orgManager.getMemberById(v3xFile.getCreateMember());
			Attachment wordAttachment = uploadFile(basePath + "new_"+v3xFile.getFilename(), v3xOrgMember.getLoginName(), attachments.get(0).getReference());
			
			Map<String, Attachment> resultMap = new HashMap<String, Attachment>();
			resultMap.put("审批合同正文", wordAttachment);
			
			List<File> files = new ArrayList<File>();
			files.add(newFile);
			files.add(toFile);
			// -- 删除临时文件
			FileUtils.delete(files);
			
			return resultMap;
		}
		return null;
	}
	
	
	
	private Attachment uploadFile(String filepath,String loginName,Long reference) throws Exception{
		FileUploadExporter uploadExporter = new FileUploadExporter();
		String processUploadStr = uploadExporter.processUpload(loginName, new String[]{filepath});
		Long uuid = UUIDUtil.getAbsUUIDLong();
		V3XFile vfile = fileManager.getV3XFile(Long.valueOf(processUploadStr));
		Attachment att = new Attachment(vfile);
		att.setReference(reference);
		att.setCategory(66);
		att.setSubReference(uuid);
		att.setIdIfNew();
		attachmentDAO.save(att);
		return att;
	}

	public void setAttachmentManager(AttachmentManager attachmentManager) {
		this.attachmentManager = attachmentManager;
	}

	public void setFileManager(FileManager fileManager) {
		this.fileManager = fileManager;
	}

	public void setAttachmentDAO(AttachmentDAO attachmentDAO) {
		this.attachmentDAO = attachmentDAO;
	}

}
